<template>
  <div>
    <el-form :model="baseNotice" label-width="100px" :rules="baseNoticeRules" v-loading="loading" ref="baseNotice">
      <el-form-item label="系统类型" prop="type" style="width: 340px">
        <el-select v-model="baseNotice.accountType" prop="accountType" placeholder="选择系统类型" :change="handleChangeAccountType" style="width:100%">
          <el-option label="全部" value="-1"></el-option>
          <el-option label="运营" value="0" ></el-option>
          <el-option label="供应商" value="1"></el-option>
          <el-option label="门店" value="2"></el-option>
          <el-option label="会员" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="公告类型" prop="type" style="width: 340px">
        <el-select v-model="baseNotice.type" prop="type" placeholder="选择公告类型" :change="handleChangeType" style="width:100%">
          <el-option label="公告" value="0"></el-option>
          <el-option label="提示消息" value="1" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title" style="width: 340px">
        <el-input v-model="baseNotice.title"></el-input>
      </el-form-item>
      <el-form-item label="内容" style="width: 650px;" prop="content">
        <!-- bidirectional data binding（双向数据绑定） -->
        <quill-editor style="width: 1050px;line-height:30px;" ref="myTextEditor"
                      v-model="baseNotice.content"
                      :options="editorOption"
                      @blur="onEditorBlur($event)">
          <div id="toolbar" scope="toolbar">
            <!-- Add a bold button -->
            <button class="ql-bold"></button>
            <button class="ql-italic"></button>
            <button class="ql-underline"></button>
            <button class="ql-strike"></button>
            <button class="ql-blockquote"></button>
            <button class="ql-code-block"></button>
            <button class="ql-header" value="1"></button>
            <button class="ql-header" value="2"></button>
            <button class="ql-list" value="ordered"></button>
            <button class="ql-list" value="bullet"></button>
            <button class="ql-script" value="sub"></button>
            <button class="ql-script" value="super"></button>
            <button class="ql-indent" value="-1"></button>
            <button class="ql-indent" value="+1"></button>
            <button class="ql-direction" value="rtl"></button>
            <!-- Add font size dropdown -->
            <select class="ql-size">
              <option value="small"></option>
              <!-- Note a missing, thus falsy value, is used to reset to default -->
              <option selected></option>
              <option value="large"></option>
              <option value="huge"></option>
            </select>
            <select class="ql-header">
              <option value="1"></option>
              <!-- Note a missing, thus falsy value, is used to reset to default -->
              <option value="2"></option>
              <option value="3"></option>
              <option value="4"></option>
              <option value="5"></option>
              <option value="6"></option>
              <option selected></option>
            </select>
            <select class="ql-color">
              <option selected="selected"></option>
              <option value="#e60000"></option>
              <option value="#ff9900"></option>
              <option value="#ffff00"></option>
              <option value="#008a00"></option>
              <option value="#0066cc"></option>
              <option value="#9933ff"></option>
              <option value="#ffffff"></option>
              <option value="#facccc"></option>
              <option value="#ffebcc"></option>
              <option value="#ffffcc"></option>
              <option value="#cce8cc"></option>
              <option value="#cce0f5"></option>
              <option value="#ebd6ff"></option>
              <option value="#bbbbbb"></option>
              <option value="#f06666"></option>
              <option value="#ffc266"></option>
              <option value="#ffff66"></option>
              <option value="#66b966"></option>
              <option value="#66a3e0"></option>
              <option value="#c285ff"></option>
              <option value="#888888"></option>
              <option value="#a10000"></option>
              <option value="#b26b00"></option>
              <option value="#b2b200"></option>
              <option value="#006100"></option>
              <option value="#0047b2"></option>
              <option value="#6b24b2"></option>
              <option value="#444444"></option>
              <option value="#5c0000"></option>
              <option value="#663d00"></option>
              <option value="#666600"></option>
              <option value="#003700"></option>
              <option value="#002966"></option>
              <option value="#3d1466"></option>
            </select>
            <select class="ql-background">
              <option selected="selected"></option>
              <option value="#e60000"></option>
              <option value="#ff9900"></option>
              <option value="#ffff00"></option>
              <option value="#008a00"></option>
              <option value="#0066cc"></option>
              <option value="#9933ff"></option>
              <option value="#ffffff"></option>
              <option value="#facccc"></option>
              <option value="#ffebcc"></option>
              <option value="#ffffcc"></option>
              <option value="#cce8cc"></option>
              <option value="#cce0f5"></option>
              <option value="#ebd6ff"></option>
              <option value="#bbbbbb"></option>
              <option value="#f06666"></option>
              <option value="#ffc266"></option>
              <option value="#ffff66"></option>
              <option value="#66b966"></option>
              <option value="#66a3e0"></option>
              <option value="#c285ff"></option>
              <option value="#888888"></option>
              <option value="#a10000"></option>
              <option value="#b26b00"></option>
              <option value="#b2b200"></option>
              <option value="#006100"></option>
              <option value="#0047b2"></option>
              <option value="#6b24b2"></option>
              <option value="#444444"></option>
              <option value="#5c0000"></option>
              <option value="#663d00"></option>
              <option value="#666600"></option>
              <option value="#003700"></option>
              <option value="#002966"></option>
              <option value="#3d1466"></option>
            </select>
            <select class="ql-font">
              <option value="serif"></option>
              <!-- Note a missing, thus falsy value, is used to reset to default -->
              <option value="monospace"></option>
              <option selected></option>
            </select>
            <select class="ql-align">
              <option selected></option>
              <option value="center"></option>
              <!-- Note a missing, thus falsy value, is used to reset to default -->
              <option value="right"></option>
              <option value="justify"></option>
            </select>
            <!-- Add subscript and superscript buttons -->
            <button class="ql-clean" ></button>
            <button class="ql-link"></button>
            <!--<button class="ql-image"></button>-->
            <!--<button class="ql-video"></button>-->
            <!--<button @click="customButtonClick">custom button</button>-->
          </div>
        </quill-editor>
      </el-form-item>
      <el-form-item label="附件" style="width: 500px;margin-top: 25px">
        <el-upload
          class="upload-demo"
          :auto-upload="false"
          ref="upload"
          accept=".doc,.docx,.xls,.xlsx"
          action="/smartLight/web/baseNotice/uploadNotice.htm"
          :on-remove="removeFun"
          :on-change="onChangeFunc"
          :on-success="successFun"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <span scope="tip" class="el-upload__tip" style="color: red;">* 只能上传doc，docx，xls，xlsx 文件，且不超过20M</span>
        </el-upload>
      </el-form-item>
      <el-form-item style="margin-left: 200px">
        <el-button @click="goBaseNotice">取消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="saveNoticeLoading">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script type="text/ecmascript-6">
  import { quillEditor } from 'vue-quill-editor'
  import {sessionOut} from '../../smartlight/common/js/util.js'
  export default {
    // props: {
    //   editParams: {
    //     type: Object,
    //     default () {
    //       return {}
    //     }
    //   }
    // },
    data () {
      // 校验内容信息
      var checkContent = (rule, value, callback) => {
        value = value.replace(/<[^<>]+?>/g, '')
        if (value.trim() === '') {
          callback(new Error('请输入内容'))
        } else if (value.trim().length > 800) {
          callback(new Error('内容超出长度限制'))
        } else {
          callback()
        }
      }
      return {
        saveNoticeLoading: false, // 保存公告的的动画按钮
        loading: true,
        addNotice: {
          id: 0,
          accountType: '-1',
          noticeType: '0',
          type: '0',
          title: '',
          content: ''
        },
        pageType: 'add',
        changeFile: false,
        dataMsg: '',
        isChooseFile: false,
        fileList: [],
        loginType: 0,
        baseNotice: {
          id: 0,
          accountType: '-1',
          type: '0',
          title: '',
          content: '',
          file: ''
        },
        name: 'base-example',
        fileName: '',
        editorOption: {
          modules: {
            toolbar: '#toolbar'
          },
          placeholder: '请输入公告内容...',
          readOnly: false
        },
        baseNoticeRules: {
          accountType: [
            {required: true, message: '请选择系统类型', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择公告类型', trigger: 'blur'}
          ],
          title: [
            {required: true, message: '请输入标题', trigger: 'blur'}
          ],
          content: [
            {required: true, validator: checkContent, trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      // 判断是否登录超时
      checkIfLogin () {
        var user = sessionStorage.getItem('user')
        if (!user) {
          this.$alert('登录超时，请重新登录！', ' ', {
            type: 'warning'
          }).then(() => {
            this.$router.push({path: '/login'})
            sessionStorage.clear()
          })
        } else {
          return true
        }
      },
      // 公告类型
      handleChangeType: function (val) {
        this.baseNotice.type = val
      },
      // 公告针对账户类型展示
      handleChangeAccountType: function (val) {
        this.baseNotice.accountType = val
      },
      // 附件只能上传一个文件
      onChangeFunc (file, fileList) {
        const isLt2M = file.size / 1024 / 1024 < 20
        if (!isLt2M) {
          this.$message.error('上传附件大小不能超过 20MB!')
          this.$refs.upload.clearFiles()
          this.isChooseFile = false
          return isLt2M
        } else {
          if (fileList.length > 1) {
            fileList.splice(0, 1)
            this.isChooseFile = true
            this.changeFile = true
          } else if (fileList.length === 0) {
            this.isChooseFile = false
            this.changeFile = false
          } else {
            this.isChooseFile = true
            this.changeFile = true
          }
        }
      },
      // 系统公告【新增】
      onSubmit () {
        if (!this.checkIfLogin()) {
          return
        }
        this.baseNotice.content = this.$refs.myTextEditor.value
        this.$refs.baseNotice.validate((valid) => {
          if (valid) {
            if (this.isChooseFile) {
              if (this.changeFile) {
                this.$refs.upload.submit()
              } else {
                let params = {
                  type: 0,
                  id: this.baseNotice.id,
                  noticeType: this.baseNotice.type,
                  accountType: this.baseNotice.accountType,
                  title: encodeURIComponent(this.baseNotice.title),
                  content: encodeURIComponent(this.baseNotice.content),
                  file: this.baseNotice.file
                }
                this.saveNoticeLoading = true
                this.publicSave(params)
              }
            } else {
              let params = {
                type: 0,
                id: this.baseNotice.id,
                noticeType: this.baseNotice.type,
                accountType: this.baseNotice.accountType,
                title: encodeURIComponent(this.baseNotice.title),
                content: encodeURIComponent(this.baseNotice.content),
                file: this.baseNotice.file
              }
              this.publicSave(params)
            }
          }
        })
      },
      // 保存修改的公共方法
      publicSave (params) {
        this.$http.post('/smartLight/web/baseNotice/saveNotice.htm', params).then(response => {
          this.saveNoticeLoading = true
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.loading = false
            this.$message({
              showClose: true,
              message: '操作成功',
              type: 'success'
            })
            // this.$emit('clickNotice', 'success') // 成功之后返回父组件
            this.$router.push({path: '/baseNotice'})
            this.$store.dispatch('updatelocationpath', '/baseNotice')
            var breads = this.$store.state.breads
            breads.splice(breads.length - 1, 1)
            this.$store.dispatch('updateBreads', breads)
          } else if (resBody.isSuccess === 2) {
            this.loading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      // 时间转换
      formatTimeStr (createTime) {
        var d = new Date(createTime)
        var year = d.getFullYear()
        var month = ((d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1))
        var date = (d.getDate() < 10 ? '0' + d.getDate() : d.getDate())
        var hour = (d.getHours() < 10 ? '0' + d.getHours() : d.getHours())
        var minute = (d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes())
        var second = (d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds())
        return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
      },
      // 文件上传成功事件
      successFun (response, file, fileList) {
        var resBody = JSON.parse(this.decode(response))
        if (resBody.res === 0) { // 附件上传成功开始保存或修改
          var fileUrl = resBody.url
          var params = {
            type: 0,
            id: this.baseNotice.id,
            noticeType: this.baseNotice.type,
            accountType: this.baseNotice.accountType,
            title: encodeURIComponent(this.baseNotice.title),
            content: encodeURIComponent(this.baseNotice.content),
            file: fileUrl
          }
          this.publicSave(params)
        } else {
          this.$refs.upload.clearFiles()
          this.$message({
            showClose: true,
            message: resBody.errorMsg,
            type: 'error'
          })
        }
      },
      // 文件上传移除事件
      removeFun (file) {
        this.isChooseFile = false
        this.changeFile = false
        this.baseNotice.file = ''
      },
      // 编辑器失去焦点获取内容
      onEditorBlur (editor) {
        this.baseNotice.content = this.$refs.myTextEditor.value
        this.$refs.baseNotice.validateField('content')
      },
      // 根据id查询公告对象
      getById () {
        var para = {id: this.baseNotice.id, type: this.loginType}
        this.$http.post('/smartLight/web/baseNotice/getById.htm', para).then(response => {
          var resBody = response.body
          var notice = resBody.result
          if (resBody.isSuccess === 0) {
            this.loading = false
            if (notice !== null) {
              this.baseNotice = notice
              this.baseNotice.type = notice.type.toString()
              this.baseNotice.accountType = notice.accountType.toString()
              if (notice.file !== '') {
                this.baseNotice.file = notice.file
                var urls = notice.file.split('/')
                this.fileName = urls[urls.length - 1] // 附件名称
                var file = {name: this.fileName, url: this.baseNotice.file}
                this.fileList.push(file)
                this.isChooseFile = true
              } else {
                this.isChooseFile = false
              }
            }
          } else if (resBody.isSuccess === 2) {
            this.loading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      goBaseNotice () { // 取消点击事件，返回原页面
        // this.$emit('clickNotice', '')
        this.$router.push({path: '/baseNotice'})
        this.$store.dispatch('updatelocationpath', '/baseNotice')
        var breads = this.$store.state.breads
        breads.splice(breads.length - 1, 1)
        this.$store.dispatch('updateBreads', breads)
      }
    },
    mounted () {
      var user = sessionStorage.getItem('user')
      if (user) {
        user = JSON.parse(user)
        this.loginType = user.type
        this.pageType = this.$route.params.pageType
        // 刷新操作
        if (this.pageType === undefined) {
          this.$router.push({path: '/baseNotice'})
          return
        }
        if (this.pageType === 'edit') {
          this.baseNotice.id = this.$route.params.id
          this.getById()
        }
        this.$nextTick(() => {
          this.loading = false
        })
      }
    },
    components: {
      quillEditor
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">
  .ql-picker-item
    line-height:30px
  .ql-container
    .ql-editor
      min-height:210px
</style>
